using BXS.API.Models;

namespace BXS.API.Services
{
    /// <summary>
    /// 微信支付服务
    /// </summary>
    public class WeChatPayService
    {
        /// <summary>
        /// 统一下单
        /// </summary>
        /// <param name="order">订单信息</param>
        /// <returns>支付结果</returns>
        public async Task<PaymentResult> UnifiedOrderAsync(Order order)
        {
            // 模拟微信支付统一下单API调用
            try
            {
                // 模拟网络延迟
                await Task.Delay(500);

                // 构造微信支付参数
                var wechatPayParams = new
                {
                    appid = "wx_test_appid",           // 小程序ID
                    mch_id = "test_mch_id",            // 商户号
                    device_info = "WEB",               // 设备号
                    nonce_str = GenerateNonceStr(),    // 随机字符串
                    body = GetOrderDescription(order), // 商品描述
                    out_trade_no = order.OrderNo,      // 商户订单号
                    total_fee = (int)(order.TotalAmount * 100), // 订单金额(分)
                    spbill_create_ip = "127.0.0.1",   // 终端IP
                    notify_url = "https://api.bxs.com/payment/notify", // 通知地址
                    trade_type = "JSAPI",              // 交易类型
                    openid = "test_openid"             // 用户openid
                };

                // 模拟微信支付API响应
                var response = new
                {
                    return_code = "SUCCESS",
                    return_msg = "OK",
                    appid = wechatPayParams.appid,
                    mch_id = wechatPayParams.mch_id,
                    nonce_str = wechatPayParams.nonce_str,
                    result_code = "SUCCESS",
                    prepay_id = $"wx{DateTime.Now:yyyyMMddHHmmss}{new Random().Next(1000, 9999)}",
                    trade_type = "JSAPI"
                };

                // 生成小程序支付参数
                var payParams = GeneratePayParams(response.prepay_id);

                return new PaymentResult
                {
                    Success = true,
                    TransactionId = response.prepay_id,
                    Message = "统一下单成功",
                    PayParams = payParams
                };
            }
            catch (Exception ex)
            {
                return new PaymentResult
                {
                    Success = false,
                    Message = $"支付失败：{ex.Message}"
                };
            }
        }

        /// <summary>
        /// 支付结果查询
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <returns>查询结果</returns>
        public async Task<PaymentQueryResult> QueryPaymentAsync(string orderNo)
        {
            // 模拟支付查询API
            await Task.Delay(300);

            // 模拟支付成功
            return new PaymentQueryResult
            {
                Success = true,
                OrderNo = orderNo,
                TransactionId = $"wx{DateTime.Now:yyyyMMddHHmmss}",
                TradeState = "SUCCESS",
                TotalFee = 168000, // 分
                PayTime = DateTime.Now.ToString("yyyyMMddHHmmss")
            };
        }

        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <returns>随机字符串</returns>
        private string GenerateNonceStr()
        {
            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            var random = new Random();
            return new string(Enumerable.Repeat(chars, 32)
                .Select(s => s[random.Next(s.Length)]).ToArray());
        }

        /// <summary>
        /// 获取订单描述
        /// </summary>
        /// <param name="order">订单信息</param>
        /// <returns>订单描述</returns>
        private string GetOrderDescription(Order order)
        {
            if (order.Products.Count == 1)
            {
                return order.Products[0].Name;
            }
            else
            {
                return $"{order.Products[0].Name}等{order.Products.Count}件商品";
            }
        }

        /// <summary>
        /// 生成小程序支付参数
        /// </summary>
        /// <param name="prepayId">预支付ID</param>
        /// <returns>支付参数</returns>
        private object GeneratePayParams(string prepayId)
        {
            var timeStamp = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
            var nonceStr = GenerateNonceStr();
            var package = $"prepay_id={prepayId}";

            return new
            {
                timeStamp,
                nonceStr,
                package,
                signType = "MD5",
                paySign = "mock_pay_sign" // 实际项目中需要根据微信规则生成签名
            };
        }
    }

    /// <summary>
    /// 支付查询结果
    /// </summary>
    public class PaymentQueryResult
    {
        public bool Success { get; set; }
        public string OrderNo { get; set; } = string.Empty;
        public string TransactionId { get; set; } = string.Empty;
        public string TradeState { get; set; } = string.Empty;
        public int TotalFee { get; set; }
        public string PayTime { get; set; } = string.Empty;
        public string Message { get; set; } = string.Empty;
    }
}
